<template>
    <div class="app-container add">
        <div class="add-wrap">
            <div class="form-box">
                <div class="form-title title_flex">
                    基本信息
                    <div class="order-bottom-box">
                        <div class="toggle-wrap" @click="toggle()">
                        <span class="txt">{{ isToggle ? '收起' : '展开'}}</span>
                        <span class="img">
                            <img v-if="isToggle" src="@/assets/images/up-icon.png" alt="" />
                            <img v-else src="@/assets/images/down-icon.png" alt="" />
                        </span>
                        </div>
                        <div class="btn-wrap">
                        <!-- 按钮组 -->
                        <slot name="buttonGorup"></slot>
                        </div>
                    </div>
                </div>
                <el-form :model="formData" ref="formData" :rules="rules" inline-message label-width="0"
                    label-position="left">
                    <el-form-item prop="orderNumber">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>入库单号</div>
                            <div class="select-wrap" @click="showModal">
                                <span class="val" v-if="formData.orderNumber">{{ formData.orderNumber }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="warehouseCode" v-if="isToggle">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>仓库名称</div>
                            <div class="select-wrap" @click="selectWareHousu">
                                <span class="val" v-if="formData.warehouseName">{{ formData.warehouseName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="relateType" v-if="isToggle">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>关联单据类型</div>
                            <div class="select-wrap">
                                <!-- <div class="select-wrap" @click="billModalShow = true"> -->
                                <span class="val" v-if="formData.relateTypeName">{{ formData.relateTypeName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <!-- <el-form-item prop="relateOrders">
                        <div class="form-item">
                            <div class="label">
                                <span class="required"></span>关联单号
                                <img src="@/assets/images/scan02.png" alt="" class="scan" @click.stop="handleScanCode">
                            </div>
                            <div class="select-wrap" @click="toRefType()">
                                <span class="val" v-if="formData.relateOrders">{{ formData.relateOrders }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item> -->
                    <el-form-item prop="planTime" v-if="isToggle">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>计划入库时间</div>
                            <div class="select-wrap" @click="dateShow = true">
                                <span class="val" v-if="formData.planTime">{{ formData.planTime }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="applyPerson" v-if="isToggle">
                        <div class="form-item">
                            <div class="label">
                                <!-- <span class="required"></span> -->
                                申请人
                            </div>
                            <div class="select-wrap" @click="userModalShow = true">
                                <span class="val" v-if="formData.applyPersonName">{{ formData.applyPersonName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="warehouseManagerName" v-if="isToggle">
                        <div class="form-item">
                            <div class="label">
                                <!-- <span class="required"></span> -->
                                仓管员
                            </div>
                            <div class="select-wrap" @click="warehouseUserModalShow = true">
                                <span class="val" v-if="formData.warehouseManagerName">{{ formData.warehouseManagerName
                                    }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <!--  -->
            <div class="form-box" v-if="isToggle">
                <div class="form-title">备注信息</div>
                <div class="remark-wrap">
                    <el-input type="textarea" :rows="2" v-model="formData.remark" placeholder="请输入备注信息"
                        class="textarea"></el-input>
                </div>
            </div>
            
        </div>
        <div>
        </div>
        <!-- <div class="model-footer-wrap">
            <van-button type="primary" block round color="#548af1" size="normal" :loading="btnLoading"
                loading-text="正在提交..." @click="submitAdd()">提交</van-button>
        </div> -->
        <!-- 仓库 -->
        <van-popup v-model="wareHouseModalShow" position="bottom">
            <van-picker title="仓库列表" show-toolbar :columns="wareHouseList" value-key="warehouseName"
                @confirm="onConfirm" @cancel="wareHouseModalShow = false" />
        </van-popup>
        <!-- 关联单据类型 -->
        <van-popup v-model="billModalShow" position="bottom">
            <van-picker title="关联单据类型" show-toolbar :columns="billList" value-key="typeName" @confirm="onBillConfirm"
                @cancel="billModalShow = false" />
        </van-popup>
        <!-- 申请人选择 -->
        <van-popup v-model="userModalShow" position="bottom">
            <van-picker title="申请人列表" show-toolbar :columns="userList" value-key="nickname" @confirm="onUserConfirm"
                @cancel="userModalShow = false" />
        </van-popup>
        <!-- 仓管员 -->
        <van-popup v-model="warehouseUserModalShow" position="bottom">
            <van-picker title="仓管员列表" show-toolbar :columns="warehouseUserList" value-key="nickname"
                @confirm="onWarehouseUserConfirm" @cancel="warehouseUserModalShow = false" />
        </van-popup>
        <!-- 时间选择 -->
        <van-calendar v-model="dateShow" color="#548AF1" :min-date="minDate" @confirm="onDateConfirm" />
        <ruleDialog :show.sync="modalShow" :value.sync="formData.orderNumber" @confirm="confirm"></ruleDialog>
    </div>
</template>
<script>
import CommonHeader from "@/components/CommonHeader";
import CommonMain from "@/components/CommonMain/index.vue";
import { getRelateType, getUserList, getWarehouseUserList, pdaAdd, productOrdersList, materialListByRelate, workordersSimple, getDefaultWarehouse, getNumRuleDetailByType } from '@/api/inventory'
import { queryRepositoriesIsolationList, queryAllWareHoseList } from '@/api/allocation'
import { reqStateChange, scanCodeRuleGet, materialsList, newAddBarCode } from '@/api/inventory'
import { getUserInfo } from '@/api/user'
import ruleDialog from "@/views/allocation/components/ruleDialog.vue";
import { Toast } from "vant";

export default {
    components: { CommonHeader, ruleDialog, CommonMain },
    data() {
        return {
            isToggle: false,
            minDate: new Date(2010, 0, 1),
            btnLoading: false,
            formData: {
                orderNumber: '',
                warehouseName: '',
                warehouseCode: '',
                applyPersonName: '',
                applyPerson: '',
                warehouseManagerName: '',
                relateTypeName: '采购订单',
                relateType: 'purchaseOrder',
                relateOrders: '',
                planTime: '',
                inOrOutType: 'purchase' //出入库类型（purchase:采购入库单 applicationReturn:生产退料入库 workOrderComplete:生产入库 ）
            },
            rules: {
                orderNumber: [
                    { required: true, message: '请选择', trigger: 'change' },
                ],
                warehouseName: [
                    { required: true, message: '请选择', trigger: 'change' },
                ],
                warehouseCode: [
                    { required: true, message: '请选择', trigger: 'change' },
                ],
                relateType: [
                    { required: true, message: '请选择', trigger: 'change' },
                ],
                // relateOrders: [
                //     { required: true, message: '请选择', trigger: 'change' },
                // ],
                planTime: [
                    { required: true, message: '请选择', trigger: 'change' },
                ],
                applyPerson: [
                    { required: false, message: '请选择', trigger: 'change' },
                ],
                warehouseManagerName: [
                    { required: false, message: '请选择', trigger: 'change' },
                ],

            },
            wareHouseModalShow: false,
            wareHouseList: [],
            warehouseUserList: [],
            warehouseUserModalShow: false,
            billModalShow: false,
            billList: [],
            userModalShow: false,
            userList: [],
            dateShow: false,
            modalShow: false,
            userInfo: {},
            warehouseUserInfo: {} // 已选择的仓库信息
        }

    },
    async created() {
        await this.getUserInfo()
        this.getAllWarehouse()
        // this.getRelateTypeList()
        this.getUserList()
        this.initrelateType()
    },
    methods: {
        // 判断是否有默认仓库
        getDefaultWarehouseInfo() {
            getDefaultWarehouse({ type: 1 }).then(res => {
                const { data, code } = res.data
                if (code === '200' && data && data.warehouseCode) {
                    this.onConfirm(data)
                }
            })
        },
        async initrelateType() {
            const formData = JSON.parse(sessionStorage.getItem('currentFormData')) || {}
            if (formData.orderNumber) {
                this.formData = formData
            } else {
                this.getDefaultWarehouseInfo()
            }
            // 计划时间默认当前日期
            if (!formData.planTime) {
                this.formData.planTime = this.formatDate(new Date());
            }
            const loading = this.$loading({
                lock: true,
                text: '加载中',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            const list = await this.getRelateTypeList();
            const wList = await this.getAllWarehouse();
            loading.close();
            if (this.$route.query.relateType) {
                const data = list.filter(item => item.typeCode == formData.relateType)
                const wdata = wList.filter(item => item.warehouseName == formData.warehouseName)
                this.onBillConfirm(data[1])
                if (wdata.length > 0) {
                    this.onConfirm(wdata[0], 'auto')
                }
                this.initRefNo()
            }
        },
        initRefNo() {
            if (Object.keys(this.$store.state.routerQuery.refOderList).length > 0) {
                if (this.formData.relateType == "purchaseReceipt") {
                    this.formData.relateOrders = this.$store.state.routerQuery.refOderList.receiptCode
                    this.getMaterialListByRelate(this.$store.state.routerQuery.refOderList.receiptCode)
                } else {
                    this.formData.relateOrders = this.$store.state.routerQuery.refOderList.purchaseCode
                    this.getMaterialListByRelate(this.$store.state.routerQuery.refOderList.purchaseCode)
                }
                sessionStorage.setItem("currentFormData", JSON.stringify(this.formData));
            }
        },
        toRefType() {
            if (!this.formData.relateType) {
                Toast('请选择关联类型')
                return
            }
            sessionStorage.setItem('currentFormData', JSON.stringify(this.formData))
            this.$router.push({
                path: "/addRefType",
                query: {
                    relateType: this.formData.relateType
                }
            })
        },
        // 打开入库单号
        showModal() {
            this.modalShow = true;
        },
        // 获取当前用户账号
        async getUserInfo() {
            const result = await getUserInfo()
            const { code, data, message } = result.data || {}
            if (+code === 200) {
                this.userInfo = data
            }
        },
        // 点击扫码按钮进行扫码
        async handleScanCode() {
            if (!this.formData.relateType) {
                Toast('请先选择关联单据类型')
                return
            }
            // 生产环境和开发环境
            const that = this;
            if (process.env.NODE_ENV === "production") {
                window.flutter_inappwebview.callHandler("qrCode").then((res) => {
                    if (!res) return;
                    if (this.formData.relateType === 'purchaseReceipt') { //采购收货单
                        that.getProductOrdersList(res)
                    } else if (this.formData.relateType === 'purchaseOrder') { //生产订单

                        that.getWorkordersSimple(res)
                    }
                });
            } else {
                if (this.formData.relateType === 'purchaseReceipt') { //采购收货单
                    that.getProductOrdersList("CGSH20230710001")
                } else if (this.formData.relateType === 'purchaseOrder') { //生产订单
                    that.getWorkordersSimple("CGSH20230710001")
                }
            }
        },
        // //采购收货单
        async getProductOrdersList(orderNo) {
            const result = await productOrdersList({ receiptCode: orderNo, states: '2,3' })
            const { code, data, message } = result.data || {}
            if (+code === 200) {
                if (data.records && data.records.length > 0) {
                    data.records.filter(item => {
                        if (item.receiptCode === orderNo) {
                            this.formData.relateOrders = item.receiptCode
                            this.getMaterialListByRelate(item.receiptCode)
                        }
                    })
                } else {
                    Toast('扫描的单据不符合关联条件')
                }
            } else {
                Toast(message)
            }
        },
        async getWorkordersSimple(orderNo) {
            const result = await workordersSimple({ purchaseCode: orderNo, state: '2,3' })
            const { code, data, message } = result.data || {}
            if (+code === 200) {
                if (data.records && data.records.length > 0) {
                    data.records.filter(item => {
                        if (item.purchaseCode === orderNo) {
                            this.formData.relateOrders = item.purchaseCode
                            this.getMaterialListByRelate(item.purchaseCode)
                        }
                    })
                } else {
                    Toast('扫描的单据不符合关联条件')
                }
            } else {
                Toast(message)
            }
        },
        // 通过关联单号查询物料信息和批次信息
        async getMaterialListByRelate(orderNumber) {
            const params = {
                relateOrder: orderNumber,
                relateType: this.formData.relateType
            }
            const loading = this.$loading({
                lock: true,
                text: '加载中',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            const result = await materialListByRelate(params)
            const { code, data, message } = result.data || {}
            if (+code === 200) {
                this.materialDetails = data.map(item => {
                    return {
                        productCode: item.productCode,
                        planAmount: item.planAmount,
                        actualAmount: item.actualAmount,
                        skuId: item.skuId,
                        skuName: item.skuName,
                        skuCode: item.skuCode,
                        materialRemark: item.materialRemark,
                        materialType: item.materialFields ? item.materialFields.typeName : item.materialType,
                        type: item.materialFields ? item.materialFields.type : item.type,
                        stockMaterialDetaiList: (item.barCodeDTOList || []).map(citem => {
                            return {
                                ...citem,
                                purchaseBatchNumber: item.purchaseBatchNumber
                            }
                        })
                    }
                })
                loading.close();
            } else {
                loading.close();
            }
        },
        // 打开仓库弹框
        selectWareHousu() {
            this.wareHouseModalShow = true;
        },
        // 获取所有的仓库列表
        async getAllWarehouse() {
            return new Promise(async (resolve, reject) => {
                const result = await queryRepositoriesIsolationList()
                const { code, data = {}, message } = result.data || {}
                if (+code === 200) {
                    const { records = [] } = data
                    this.wareHouseList = records
                } else {
                    Toast.success('获取仓库列表失败')
                }
                resolve(data.records)
            })
        },
        // 关联单据类型
        async getRelateTypeList() {
            return new Promise(async (resolve, reject) => {
                const result = await getRelateType()
                const { code, data, message } = result.data || {}
                if (+code === 200) {
                    this.billList = data
                } else {
                    Toast.success(message)
                }
                resolve(data)
            })
        },
        // 申请人列表
        async getUserList() {
            const result = await getUserList()
            const { code, data, message } = result.data || {}
            if (+code === 200) {
                this.userList = data.records || []
                // 默认当前账号
                if (!!this.userInfo && this.userInfo.id && this.userList.length > 0) {
                    this.userList.forEach(item => {
                        if (item.id === this.userInfo.id) {
                            this.formData.applyPersonName = item.nickname
                            this.formData.applyPerson = item.username
                        }
                    })
                }
            } else {
                Toast.success(message)
            }
        },
        // 仓管员列表
        async getWarehouseUserList(id) {
            const result = await getWarehouseUserList(id)
            const { code, data, message } = result.data || {}
            if (+code === 200) {
                this.warehouseUserList = data || []
                // 默认当前账号
                if (!!this.userInfo && this.userInfo.id && this.warehouseUserList.length > 0) {
                    this.warehouseUserList.forEach(item => {
                        if (item.id === this.userInfo.id) {
                            this.formData.warehouseManagerName = item.nickname
                            this.formData.warehouseManager = item.username
                        }
                    })
                }
            } else {
                Toast.success(message)
            }
        },
        // 选中仓管员
        onWarehouseUserConfirm(val) {
            this.formData.warehouseManagerName = val.nickname;
            this.formData.warehouseManager = val.username;
            this.warehouseUserModalShow = false;
        },
        // 选中关联单据类型
        onBillConfirm(val) {
            this.formData.relateTypeName = val.typeName;
            this.formData.relateType = val.typeCode;
            this.formData.relateOrders = ''
            this.billModalShow = false;
        },
        // 选中仓库
        onConfirm(val, type) {
            if (type == 'auto') {
                this.formData.warehouseManagerName = "";
                this.formData.warehouseManager = "";
            }
            this.formData.warehouseName = val.warehouseName;
            this.formData.warehouseCode = val.warehouseCode;
            this.formData.warehouseId = val.warehouseId;
            this.wareHouseModalShow = false;
            this.formData.warehouseManagerName = ''
            this.warehouseUserInfo = val
            this.getWarehouseUserList(val.warehouseId)
        },
        // 选中申请人
        onUserConfirm(val) {
            this.formData.applyPersonName = val.nickname;
            this.formData.applyPerson = val.username;
            this.userModalShow = false;
        },
        formatDate(val) {
            const date = new Date(val);
            const Y = date.getFullYear();
            const M = date.getMonth() + 1;
            const D = date.getDate();
            const H = date.getHours();
            const Min = date.getMinutes();
            const S = date.getSeconds();
            const formattedDate = `${Y}-${(M < 10 ? '0' : '') + M}-${(D < 10 ? '0' : '') + D} ${(H < 10 ? '0' : '') + H}:${(Min < 10 ? '0' : '') + Min}:${(S < 10 ? '0' : '') + S}`;
            return formattedDate
        },
        onDateConfirm(date) {
            this.dateShow = false;
            this.formData.planTime = this.formatDate(date);
        },
        // 确定单号
        confirm(val) {
            this.formData.orderNumber = val;
        },
        // 提交新增保存
        async submitAdd() {
            this.$refs.formData.validate((valid) => {
                // if (valid) {
                //     this.addPda()
                // }
                return valid
            });
        },
        async addPda() {
            this.btnLoading = true
            const params = {
                ...this.formData,
                materialDetails: this.materialDetails
            }
            const result = await pdaAdd(params)
            // 修改采购入库单的状态
            this.btnLoading = false
            const { code, data, message } = result.data || {}
            if (+code === 200) {
                Toast.success('新增成功')
                // await this.stateChange(data)
                sessionStorage.removeItem('currentFormData')
                this.$router.push({
                    path: "/allocationDetail",
                    query: {
                        id: data
                    }
                })
            } else {
                Toast(message)
            }
        },
        async stateChange(id) {
            let params = {
                id,
                inOrOutType: this.formData.inOrOutType,
                orderNumber: this.formData.orderNumber,
                planTime: this.formData.planTime,
                relateType: this.formData.relateType,
                warehouseCode: this.formData.warehouseCode,
                warehouseId: this.formData.warehouseId,
                state: 1
            }
            const { data } = await reqStateChange(params)
            console.log(data, '修改状态')
        },
        toggle() {
            this.isToggle = !this.isToggle
        }
    }
}
</script>

<style lang="scss">
.add-wrap {
    .el-form-item__error {
        position: absolute !important;
        top: 25px;
        right: 30px;
    }

    .el-textarea__inner {
        border: none !important;
        text-align: right !important;
    }
}
</style>
<style lang="scss" scoped>
.header-top {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 2;
}

.add-wrap {
    // padding-top: 44px;
    // padding-bottom: 80px;
    padding-bottom: 20px;
    // background-color: #f1f1f1;

    .form-box {
        margin: 12px 12px 0;
        background-color: #ffffff;
        border-radius: 4px;

        .el-form-item {
            margin-bottom: 0 !important;

        }

        .form-title {
            font-size: 16px;
            margin: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            border-bottom: 1px #F3F3F3 solid;
            position: relative;
            padding-left: 8px;

            &::before {
                content: '';
                width: 4px;
                height: 14px;
                background-color: #548AF1;
                position: absolute;
                left: 0;
                top: 13px;
            }
        }

        .form-item {
            margin: 0 7px;
            padding: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px #F3F3F3 dotted;
            font-size: 13px;
            color: #333333;

            .label {
                display: flex;
                align-items: center;

                .required {
                    content: '';
                    color: #FF0000;
                    display: inline-block;
                    width: 6px;
                    height: 6px;
                    background: url('../../../assets/images/required.png') no-repeat;
                    background-size: 100% 100%;
                    margin-right: 4px;
                }

                .scan {
                    width: 19px;
                    height: 19px;
                    margin-left: 9px;
                }
            }

            .info-wrap {
                text-align: right;

                .code {
                    color: #548AF1;

                }
            }

            input {
                width: 100%;
                border: none;
                text-align: right;
            }

            .select-wrap {
                color: #999999;

                .val {
                    color: #333333;
                }

                i {
                    margin-left: 5px;
                    color: #909090;
                }
            }
        }

        .remark-wrap {
            padding: 6px 0;

            .textarea {
                // height: 35px;
                width: 100%;
                border: none;
                font-size: 14px;
                color: #333333;

            }
        }
    }

}

.scan-img {
    position: fixed;
    bottom: 13.5vh;
    right: 0;
    // transform: translateX(-50%);
    width: 82px;
    height: 82px;
    z-index: 2;
}

.model-content {
    padding: 25px 10px 20px 26px;

    .name {
        font-size: 14px;
        color: #666666;
    }

    .value {
        font-size: 16px;
        color: #548af1;
        margin-top: 10px;
    }
}

.common-bottom {
    height: 80px;
}
.title_flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.order-bottom-box {
    height: 52px;
    padding: 0 18px 0 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .toggle-wrap{
      color: #999999;
      font-size: 14px;
      display: flex;
      align-items: center;
      .img{
        width: 11px;
        height: 13px;
        display: inline-block;
        margin-left: 4px;
        margin-top: 3px;
        img{
          width: 100%;
          height: 100%;
        }
      }
    }
    .btn-wrap{
      display: flex;
      .btn{
        width: 64px;
        height: 32px;
        border: 1px #4286F5 solid;
        border-radius: 4px;
        margin-left: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        color: #4286F5;
        &.btn-01{
          background: #4286F5;
          color: #ffffff;
        }
      }
    }
  }
</style>
